import { createRoleData, editRoleData, postRoleListData, deleteRoleById } from '@/service/role/role'
import type { IRoleList } from '@/types/role/role'
import { notification } from '@/utils/notification'
import { defineStore } from 'pinia'

const useRoleStore = defineStore('role', {
  state: () => ({
    roleList: [] as IRoleList[],
    totalCount: 0
  }),
  actions: {
    // 角色列表
    async postRoleListDataAction(data?: any) {
      // 1.获取角色列表数据
      const roleListRes = await postRoleListData(data)

      // 2.存储角色列表数据
      const { list, totalCount } = roleListRes.data
      this.roleList = list
      this.totalCount = totalCount
    },
    // 删除角色
    async deleteRoleByIdAction(id: number) {
      // 1.调用接口
      const deleteroleRes = await deleteRoleById(id)

      // 2.消息提示
      if (deleteroleRes.code === 0) {
        // 2.1删除成功
        notification('success', deleteroleRes.data)
        // 2.2请求新的数据
        this.postRoleListDataAction({ size: 10, offset: 0 })
      } else {
        //2.3删除失败
        notification('error', deleteroleRes.data)
      }
    },
    // 新建角色
    async createRoleDataAction(userInfo: any) {
      // 1.调用接口
      const createroleRes = await createRoleData(userInfo)

      // 2.消息提示
      if (createroleRes.code === 0) {
        // 2.1新建成功
        notification('success', createroleRes.data)
        // 2.2请求新的数据
        this.postRoleListDataAction({ size: 10, offset: 0 })
      } else {
        //2.3新建失败
        notification('error', createroleRes.data)
      }
    },
    //编辑角色
    async editRoleDataAction(id: number, userInfo: any) {
      // 1.调用接口
      const editroleRes = await editRoleData(id, userInfo)
      // 2.消息提示
      if (editroleRes.code === 0) {
        // 2.1编辑成功
        notification('success', editroleRes.data)
        // 2.2请求新的数据
        this.postRoleListDataAction({ size: 10, offset: 0 })
      } else {
        //2.3编辑失败
        notification('error', editroleRes.data)
      }
    }
  }
})

export default useRoleStore
